import lib from '../ThreeLib.js'

const defAttr = () => ({
    gl: null,
    children: [],
})

//世界对象
export default class Scene {
    constructor(attr) {
        Object.assign(this, defAttr(), attr);
    }

    init() {
        const { gl, children } = this;
        children.forEach(element => {
            element.init(gl);
        });
    }

    add(...elements) {
        const { gl, children } = this;
        elements.forEach(u => {
            children.push(u);
            u.parent = this;
            u.init(gl);
        })
    }

    remove(element) {
        const { children } = this;
        const i = children.indexOf(element);
        if (i != -1) {
            children.splice(i, 1);
        }
    }

    setUniform(name, uniform) {
        const { children } = this;
        children.forEach(u => {
            u.mat.setData(name, uniform);
        })
    }

    setAttrib(name, attrib) {
        const { children } = this;
        children.forEach(u => {
            u.geo.setData(name, attrib);
        })
    }

    draw() {
        const { gl, children } = this;
        lib.clearCanvas(gl, [0, 0, 0, 1]);
        children.forEach(u => {
            u.update(gl);
            u.draw(gl);
        })
    }
}